<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>history</title>
  </head>
  <body style="width: 100%; height: 100%; background: green">
    <button id="btn">切换</button>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        console.log("url:", location.pathname);
      });

      // 1/【注意】用 pushstate 方式，浏览器不会刷新页面
      document.querySelector("#btn").addEventListener("click", function () {
        const state = { name: "page1" };
        console.log("切换路由到", "page1");
        history.pushState(state, "", "page1");
      });

      //监听浏览器前进、后退
      window.onpopstate = (event) => {
        console.log("onpopstate", event.state, location.pathname);
      };
    </script>
  </body>
</html>
